package com.augrain.common.utils;


import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.http.HttpStatus;

import java.io.Serializable;

/**
 * 响应信息主体
 */
@ToString
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class RestResponse<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	private int code;

	@Getter
	@Setter
	private String msg;

	@Getter
	@Setter
	private T data;

	public static <T> RestResponse<T> ok() {
		return build(null, HttpStatus.OK.value(), "success");
	}

	public static <T> RestResponse<T> ok(T data) {
		return build(data, HttpStatus.OK.value(), "success");
	}

	public static <T> RestResponse<T> ok(T data, String msg) {
		return build(data,HttpStatus.OK.value(), msg);
	}

	public static <T> RestResponse<T> ok(T data, int code, String msg) {
		return build(data,code, msg);
	}

	public static <T> RestResponse<T> batch(int success, int fail, String msg) {
		if (fail == 0) {
			return ok(null, "操作成功");
		}
		return build(null,HttpStatus.OK.value(), "已成功" + success + "条，失败" + fail + "条，失败原因：" + msg);
	}

	public static <T> RestResponse<T> failed() {
		return build(null, HttpStatus.INTERNAL_SERVER_ERROR.value(), "failure");
	}

	public static <T> RestResponse<T> failed(String msg) {
		return build(null, HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
	}

	public static <T> RestResponse<T> failed(T data) {
		return build(data, HttpStatus.INTERNAL_SERVER_ERROR.value(), "failure");
	}

	public static <T> RestResponse<T> failed(T data, String msg) {
		return build(data, HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
	}

	public static <T> RestResponse<T> build(T data, int code, String msg) {
		RestResponse<T> apiResult = new RestResponse<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}

	public RestResponse(T data) {
		super();
		this.data = data;
	}

	public RestResponse(T data, String msg) {
		super();
		this.data = data;
		this.msg = msg;
	}

	@JsonIgnore
	public boolean isSuccess() {
		return HttpStatus.OK.value() == code;
	}
}
